package com.whfc.emp.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.whfc.base.entity.AppMessage;
import com.whfc.base.service.MessageService;
import com.whfc.common.constant.QueueConst;
import com.whfc.common.enums.AppWarnModuleType;
import com.whfc.common.enums.ApprovalResult;
import com.whfc.common.exception.BizException;
import com.whfc.common.result.ResultEnum;
import com.whfc.common.third.helmet.HelmetProperties;
import com.whfc.common.util.DateUtil;
import com.whfc.emp.dao.AppEmpMapper;
import com.whfc.emp.dao.AppEmpWarnMapper;
import com.whfc.emp.dao.AppEmpWarnRuleMapper;
import com.whfc.emp.dao.AppWorkPlanMapper;
import com.whfc.emp.dto.AppEmpWorkPlanWarnDTO;
import com.whfc.emp.entity.AppEmp;
import com.whfc.emp.entity.AppEmpWarn;
import com.whfc.emp.entity.AppEmpWarnRule;
import com.whfc.emp.entity.AppWorkPlan;
import com.whfc.emp.service.AppEmpWorkPlanWarnService;
import com.whfc.emp.service.AppWorkPlanService;
import com.whfc.emp.dto.WorkPlanPersonCheckResultDTO;
import com.whfc.emp.dto.AppEmpDTO;
import com.whfc.entity.dto.Apply.rep.WorkPlan;
import com.whfc.entity.dto.Apply.req.WorkPlanCreatePlanReq;
import com.whfc.entity.dto.msg.AppMsgToUserDTO;
import com.whfc.entity.dto.msg.PushMsgDTO;
import com.whfc.fuum.entity.SysEmpUser;
import com.whfc.fuum.entity.SysUser;
import com.whfc.fuum.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.Collections.*;

/**
 * 工作计划服务实现类
 */
@Slf4j
@DubboService(interfaceClass = AppWorkPlanService.class, version = "1.0.0", timeout = 30000)
public class AppWorkPlanServiceImpl implements AppWorkPlanService {

    @Resource
    private AppWorkPlanMapper appWorkPlanMapper;

    @Autowired
    private AppEmpMapper appEmpMapper;

    @DubboReference(interfaceClass = SysUserService.class, version = "1.0.0")
    private SysUserService sysUserService;

    @Autowired
    private AppEmpWarnRuleMapper appEmpWarnRuleMapper;

    @Autowired
    private AppEmpWarnMapper appEmpWarnMapper;

    @Autowired
    private AppEmpWorkPlanWarnService appEmpWorkPlanWarnService;

    @DubboReference(interfaceClass = MessageService.class, version = "1.0.0")
    private MessageService messageService;

    @Autowired
    private HelmetProperties helmetProperties;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Override
    public AppWorkPlan selectById(Integer id) {
        if (id == null) {
            return null;
        }
        return appWorkPlanMapper.selectByPrimaryKey(id);
    }

    @Override
    public int deleteById(Long id) {
        if (id == null) {
            return 0;
        }
        return appWorkPlanMapper.deleteByPrimaryKey(id);
    }

    @Override
    public WorkPlanCreatePlanReq insertSelective(AppWorkPlan record) {
        record.setAuditStatus(ApprovalResult.PENDING.getValue());
        record.setIsDeleted(0);
        WorkPlanCreatePlanReq workPlanCreatePlanReq = new WorkPlanCreatePlanReq();
        System.out.println(JSON.toJSONString(record));
        appWorkPlanMapper.insertSelective(record);
        workPlanCreatePlanReq.setId(record.getId());
        return workPlanCreatePlanReq;
    }

    @Override
    public int updateSelectiveById(AppWorkPlan record) {
        if (record == null || record.getId() == null) {
            return 0;
        }
        System.out.println("入场人员" + record.getConstructionWorkers());
        return appWorkPlanMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public List<AppWorkPlan> selectList(Integer auditStatus, Long createUserId) {
        return appWorkPlanMapper.selectWorkPlanList(auditStatus, createUserId);
    }

    @Override
    public List<WorkPlan> selectWorkPlanList(List<Integer> deptId, Integer createUserId,
            String createTimeBegin, String createTimeEnd) {

        return appWorkPlanMapper.selectWorkPlanAddList(deptId, createUserId, createTimeBegin, createTimeEnd);
    }

    @Override
    public int updateAuditStatus(AppWorkPlan record) {
        if (record == null || record.getId() == null || record.getAuditStatus() == null) {
            return 0;
        }
        return appWorkPlanMapper.updateAuditStatus(record);
    }

    @Override
    public List<AppWorkPlan> selectAppWorkPlanList(Integer auditStatus, Integer userId, Integer id) {
        return appWorkPlanMapper.selectAppWorkPlanList(auditStatus, userId, id);
    }

    @Override
    public WorkPlan getWorkPlanById(Integer id) {
        return appWorkPlanMapper.getWorkPlanById(id);
    }

    @Override
    public List<WorkPlan> selectWorkPlanListWithTimeRange(List<Integer> deptId, Integer createUserId,
            String createTimeBegin, String createTimeEnd,
            LocalDateTime startTimeBegin, LocalDateTime startTimeEnd,
            LocalDateTime endTimeBegin, LocalDateTime endTimeEnd, Integer auditStatus) {
        return appWorkPlanMapper.selectWorkPlanListWithTimeRange(deptId, createUserId,
                createTimeBegin, createTimeEnd,
                startTimeBegin, startTimeEnd,
                endTimeBegin, endTimeEnd,auditStatus);
    }

//    @Scheduled(fixedDelay = 5*60*1000)
    @Override
    public List<WorkPlanPersonCheckResultDTO> checkWorkPlanPersonCount() {
        List<WorkPlanPersonCheckResultDTO> resultList = new ArrayList<>();
        
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 计算前后5分钟的时间范围
        LocalDateTime startTimeBegin = now.minusMinutes(5);
        LocalDateTime startTimeEnd = now.plusMinutes(5);
        
        // 查询已审核且开始时间在当前时间前后5分钟内的工作计划
        List<WorkPlan> workPlans = appWorkPlanMapper.selectWorkPlanListWithTimeRange(
            null, null, null, null, 
            startTimeBegin, startTimeEnd, null, null, 
            ApprovalResult.APPROVE.getValue()
        );
        
        if (workPlans == null || workPlans.isEmpty()) {
            log.info("{} - {} 未查询到需要校验出勤人员的工作计划", startTimeBegin, startTimeEnd);
            return resultList;
        }
        
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String checkTime = sdf.format(new Date());
        
        for (WorkPlan workPlan : workPlans) {
            // 统计工作计划中的施工人员数量
            Integer planPersonCount = getConstructionWorkerCount(workPlan.getConstructionWorkers());
            
            // 模拟获取宇视监控上报人数（这里需要根据实际监控系统接口实现）
            Integer monitorPersonCount = getMonitorPersonCount(workPlan.getId(), workPlan.getWorkAreaId());
            
            // 校验人数是否一致
            boolean checkResult = Objects.equals(planPersonCount, monitorPersonCount);
            
            // 获取旁站监护人员信息
            List<Integer> guardianIds = getGuardianIds(workPlan);
            List<String> guardianNames = getGuardianNames(guardianIds);
            
            // 构建校验结果
            WorkPlanPersonCheckResultDTO result = new WorkPlanPersonCheckResultDTO();
            result.setWorkPlanId(workPlan.getId());
            result.setPlanName(workPlan.getPlanName());
            result.setPlanStartTime(workPlan.getPlanStartTime());
            result.setPlanPersonCount(planPersonCount);
            result.setMonitorPersonCount(monitorPersonCount);
            result.setCheckResult(checkResult);
            result.setCheckTime(checkTime);
            
            // 如果不一致，生成报警消息并推送给旁站监护人员
            if (!checkResult) {
                String alarmMessage = generateAlarmMessage(workPlan, planPersonCount, monitorPersonCount);
                result.setAlarmMessage(alarmMessage);
                
                // 推送报警消息给旁站监护人员
                pushAlarmMessageToGuardians("工作计划到场人员数量报警", alarmMessage, workPlan, guardianIds);
            }
            
            resultList.add(result);
        }
        
        return resultList;
    }

    /**
     * 获取工作计划中的旁站监护人员ID列表
     */
    private List<Integer> getGuardianIds(WorkPlan workPlan) {
        List<Integer> guardianIds = new ArrayList<>();
        
        // 解析guardian1Id字段（逗号分隔的ID字符串）
        if (workPlan.getGuardian1Id() != null && !workPlan.getGuardian1Id().trim().isEmpty()) {
            try {
                List<Integer> ids = Arrays.stream(workPlan.getGuardian1Id().split(","))
                        .map(String::trim)
                        .filter(s -> !s.isEmpty())
                        .map(Integer::parseInt)
                        .collect(Collectors.toList());
                guardianIds.addAll(ids);
            } catch (NumberFormatException e) {
                log.warn("解析guardian1Id失败: {}", workPlan.getGuardian1Id());
            }
        }
        
        // 解析guardian2Id字段
        if (workPlan.getGuardian2Id() != null && !workPlan.getGuardian2Id().trim().isEmpty()) {
            try {
                List<Integer> ids = Arrays.stream(workPlan.getGuardian2Id().split(","))
                        .map(String::trim)
                        .filter(s -> !s.isEmpty())
                        .map(Integer::parseInt)
                        .collect(Collectors.toList());
                guardianIds.addAll(ids);
            } catch (NumberFormatException e) {
                log.warn("解析guardian2Id失败: {}", workPlan.getGuardian2Id());
            }
        }
        
        // 解析guardian3Id字段
        if (workPlan.getGuardian3Id() != null && !workPlan.getGuardian3Id().trim().isEmpty()) {
            try {
                List<Integer> ids = Arrays.stream(workPlan.getGuardian3Id().split(","))
                        .map(String::trim)
                        .filter(s -> !s.isEmpty())
                        .map(Integer::parseInt)
                        .collect(Collectors.toList());
                guardianIds.addAll(ids);
            } catch (NumberFormatException e) {
                log.warn("解析guardian3Id失败: {}", workPlan.getGuardian3Id());
            }
        }
        
        // 解析guardian4Id字段
        if (workPlan.getGuardian4Id() != null && !workPlan.getGuardian4Id().trim().isEmpty()) {
            try {
                List<Integer> ids = Arrays.stream(workPlan.getGuardian4Id().split(","))
                        .map(String::trim)
                        .filter(s -> !s.isEmpty())
                        .map(Integer::parseInt)
                        .collect(Collectors.toList());
                guardianIds.addAll(ids);
            } catch (NumberFormatException e) {
                log.warn("解析guardian4Id失败: {}", workPlan.getGuardian4Id());
            }
        }
        
        return guardianIds;
    }

    /**
     * 根据监护人员ID获取姓名列表
     */
    private List<String> getGuardianNames(List<Integer> guardianIds) {
        if (guardianIds == null || guardianIds.isEmpty()) {
            return new ArrayList<>();
        }
        
        List<String> guardianNames = new ArrayList<>();
        try {
            // 批量查询人员信息
            List<AppEmpDTO> empList = appEmpMapper.selectByPrimaryKeyList(guardianIds);
            if (empList != null) {
                guardianNames = empList.stream()
                        .map(AppEmpDTO::getEmpName)
                        .collect(Collectors.toList());
            }
        } catch (Exception e) {
            log.error("获取监护人员姓名失败: {}", e.getMessage());
        }
        
        return guardianNames;
    }

    /**
     * 推送报警消息给旁站监护人员
     */
    private List<AppMsgToUserDTO> pushAlarmMessageToGuardians(String title, String alarmMessage, WorkPlan workPlan, List<Integer> guardianIds) {
        if (amqpTemplate == null) {
            log.error("RabbitMQ未配置，报警消息：{}", alarmMessage);
            return emptyList();
        }
        
        if (guardianIds == null || guardianIds.isEmpty()) {
            log.warn("工作计划【{}】没有配置旁站监护人员，无法推送报警消息", workPlan.getPlanName());
            return emptyList();
        }

        List<AppMsgToUserDTO> toUserList = new ArrayList<>();
        try {
            // 构建接收人列表
            for (Integer guardianId : guardianIds) {
                AppMsgToUserDTO userDTO = new AppMsgToUserDTO();
//                AppEmpDTO empInfo = appEmpMapper.selectEmpDTOById(guardianId);
                SysEmpUser sysEmpUser = sysUserService.getEmpUser(guardianId);
                if (sysEmpUser == null) continue;
                userDTO.setUserId(sysEmpUser.getSysUserId());
                // 查询监护人员详细信息，补全username和phone字段
                SysUser sysUser = sysUserService.getUserById(sysEmpUser.getSysUserId());
                if (sysUser != null) {
                    userDTO.setUsername(sysUser.getUsername()); // 设置用户名（人员姓名）
                    userDTO.setPhone(sysUser.getPhone());      // 设置手机号
                } else {
                    // 如果查询不到人员信息，设置默认值
                    userDTO.setUsername("未知用户");
                    userDTO.setPhone("");
                }
                toUserList.add(userDTO);
            }
            
            // 设置默认消息渠道：PC(3)和APP(1)
            List<Integer> msgChannelList = Arrays.asList(3, 1); // 3=后台(PC), 1=小程序(APP)
            
            // 使用PushMsgDTO封装推送消息
            PushMsgDTO pushMsgDTO = new PushMsgDTO();
            pushMsgDTO.setTitle(title);
            pushMsgDTO.setContent(alarmMessage);
            pushMsgDTO.setTime(new Date());
            pushMsgDTO.setModuleType(AppWarnModuleType.EMP.value()); // 安全报警类型
            pushMsgDTO.setMsgObjectId(String.valueOf(workPlan.getId()));
            pushMsgDTO.setDeptId(220);
            pushMsgDTO.setToUserList(toUserList);
            pushMsgDTO.setMsgChannelList(msgChannelList);
            
            // 发送到fanout.push_msg交换机
            amqpTemplate.convertAndSend(QueueConst.PUSH_MSG_EXCHANGE, "", JSON.toJSONString(pushMsgDTO));
            
            log.info("报警消息推送给旁站监护人员成功：{}，接收人：{}", alarmMessage, guardianIds);
        } catch (Exception e) {
            log.error("报警消息推送失败：{}", e.getMessage());
        }

        return toUserList;
    }

    /**
     * 统计施工人员数量
     */
    private Integer getConstructionWorkerCount(String constructionWorkers) {
        if (constructionWorkers == null || constructionWorkers.trim().isEmpty()) {
            return 0;
        }
        
        // 施工人员ID以逗号分隔，统计数量
        String[] workerIds = constructionWorkers.split(",");
        return workerIds.length;
    }

    /**
     * 获取监控上报人数（模拟实现，需要根据实际监控系统接口调整）
     */
    private Integer getMonitorPersonCount(Integer workPlanId, Integer workAreaId) {
        // TODO: 这里需要调用宇视监控系统的接口获取实际识别的人数
        // 目前先模拟返回一个随机数用于演示
        Random random = new Random();
        return random.nextInt(5) + 1; // 返回1-10之间的随机数
    }

    /**
     * 生成报警消息
     */
    private String generateAlarmMessage(WorkPlan workPlan, Integer planPersonCount, Integer monitorPersonCount) {
        return String.format("工作计划【%s】人员数量不一致！计划施工人员：%d人，监控识别人员：%d人，时间：%s", 
            workPlan.getPlanName(), planPersonCount, monitorPersonCount, workPlan.getPlanStartTime());
    }

    @Override
    public List<AppWorkPlan> listValidPlansByWorkAreaAndDate(Integer workAreaId, String currentDate) {
        if (workAreaId == null || currentDate == null) {
            return new ArrayList<>();
        }

        return appWorkPlanMapper.selectValidPlansByWorkAreaAndDate(workAreaId, currentDate);
    }

    @Override
    public List<SysUser> getGuardianListByWorkPlanId(Integer workPlanId) {
        if (workPlanId == null) {
            log.warn("工作计划ID为空，无法查询旁站监护人员");
            return new ArrayList<>();
        }
        
        try {
            // 1. 根据workPlanId查询工作计划信息
            AppWorkPlan workPlan = appWorkPlanMapper.selectByPrimaryKey(workPlanId);
            if (workPlan == null) {
                log.warn("未找到ID为{}的工作计划", workPlanId);
                return new ArrayList<>();
            }

            // 2. 解析旁站监护人员ID列表
            List<Integer> guardianIds = parseGuardianIdsFromWorkPlan(workPlan);
            if (guardianIds.isEmpty()) {
                log.info("工作计划【{}】未配置旁站监护人员", workPlan.getPlanName());
                return new ArrayList<>();
            }

            // 3. 批量查询人员信息
            List<SysUser> sysUsers = new ArrayList<>();
            for (Integer id: guardianIds){
                SysUser sysUser = sysUserService.getUserById(id);
                if (sysUser != null) sysUsers.add(sysUser);
            }
            if (sysUsers == null || sysUsers.isEmpty()) {
                log.warn("未找到ID为{}的旁站监护人员信息", guardianIds);
                return new ArrayList<>();
            }

            log.info("成功获取工作计划【{}】的旁站监护人员列表，共{}人", 
                    workPlan.getPlanName(), sysUsers.size());
            return sysUsers;
            
        } catch (Exception e) {
            log.error("获取工作计划{}的旁站监护人员列表失败：{}", workPlanId, e.getMessage());
            return new ArrayList<>();
        }
    }

    @Override
    public List<AppMsgToUserDTO> sendAlarmMessageToWorkPlanGuardians(String title, String alarmMessage, Integer workPlanId) {
        if (StringUtils.isEmpty(alarmMessage) || workPlanId == null){
//            throw new BizException(ResultEnum.FAILURE.getCode(), "缺少报警信息");
            log.error("缺少报警信息 alarmMessage:{}, workPlanId:{}", alarmMessage, workPlanId);
            return emptyList();
        }
        WorkPlan workPlan = appWorkPlanMapper.getWorkPlanById(workPlanId);
        if (workPlan == null){
//            throw new BizException(ResultEnum.FAILURE.getCode(), "无效工作计划");
            log.error("无效工作计划 {}", workPlanId);
            return emptyList();
        }
        List<Integer> guardianIds = getGuardianIds(workPlan);

        return pushAlarmMessageToGuardians(title, alarmMessage, workPlan, guardianIds);
    }

    private List<Integer> buildGuardianIds(String ids){
        if (ids != null && !ids.trim().isEmpty()) {
            try {
                return Arrays.stream(ids.split(","))
                        .map(String::trim)
                        .filter(s -> !s.isEmpty())
                        .map(Integer::parseInt)
                        .collect(Collectors.toList());
            } catch (NumberFormatException e) {
                log.warn("解析ids失败: {}", ids);
            }
        }
        return emptyList();
    }

    /**
     * 从工作计划中解析旁站监护人员ID列表
     */
    private List<Integer> parseGuardianIdsFromWorkPlan(AppWorkPlan workPlan) {
        List<Integer> guardianIds = new ArrayList<>();
        
        // 解析guardian1Id字段（逗号分隔的ID字符串）
        if (workPlan.getGuardian1Id() != null && !workPlan.getGuardian1Id().trim().isEmpty()) {
            try {
                List<Integer> ids = Arrays.stream(workPlan.getGuardian1Id().split(","))
                        .map(String::trim)
                        .filter(s -> !s.isEmpty())
                        .map(Integer::parseInt)
                        .collect(Collectors.toList());
                guardianIds.addAll(ids);
            } catch (NumberFormatException e) {
                log.warn("解析guardian1Id失败: {}", workPlan.getGuardian1Id());
            }
        }

        // 解析guardian2Id字段
        if (workPlan.getGuardian2Id() != null && !workPlan.getGuardian2Id().trim().isEmpty()) {
            try {
                List<Integer> ids = Arrays.stream(workPlan.getGuardian2Id().split(","))
                        .map(String::trim)
                        .filter(s -> !s.isEmpty())
                        .map(Integer::parseInt)
                        .collect(Collectors.toList());
                guardianIds.addAll(ids);
            } catch (NumberFormatException e) {
                log.warn("解析guardian2Id失败: {}", workPlan.getGuardian2Id());
            }
        }
        
        // 解析guardian3Id字段
        if (workPlan.getGuardian3Id() != null && !workPlan.getGuardian3Id().trim().isEmpty()) {
            try {
                List<Integer> ids = Arrays.stream(workPlan.getGuardian3Id().split(","))
                        .map(String::trim)
                        .filter(s -> !s.isEmpty())
                        .map(Integer::parseInt)
                        .collect(Collectors.toList());
                guardianIds.addAll(ids);
            } catch (NumberFormatException e) {
                log.warn("解析guardian3Id失败: {}", workPlan.getGuardian3Id());
            }
        }
        
        // 解析guardian4Id字段
        if (workPlan.getGuardian4Id() != null && !workPlan.getGuardian4Id().trim().isEmpty()) {
            try {
                List<Integer> ids = Arrays.stream(workPlan.getGuardian4Id().split(","))
                        .map(String::trim)
                        .filter(s -> !s.isEmpty())
                        .map(Integer::parseInt)
                        .collect(Collectors.toList());
                guardianIds.addAll(ids);
            } catch (NumberFormatException e) {
                log.warn("解析guardian4Id失败: {}", workPlan.getGuardian4Id());
            }
        }
        
        return guardianIds;
    }

    @Override
    public List<AppEmp> getWorkers(Integer workPlanId) {
        if (workPlanId == null) {
            log.warn("工作计划ID为空，无法查询施工人员");
            return new ArrayList<>();
        }

        try {
            // 1. 根据workPlanId查询工作计划信息
            AppWorkPlan workPlan = appWorkPlanMapper.selectByPrimaryKey(workPlanId);
            if (workPlan == null) {
                log.warn("未找到ID为{}的工作计划", workPlanId);
                return new ArrayList<>();
            }

            // 2. 解析施工人员ID列表
            List<String> sysUserIds = parseConstructionWorkerIds(workPlan);
            if (sysUserIds.isEmpty()) {
                log.info("工作计划【{}】未配置施工人员", workPlan.getPlanName());
                return new ArrayList<>();
            }

            // 3. 获取施工人员详细信息
            List<AppEmp> workers = getWorkerDetails(sysUserIds);

            log.info("成功获取工作计划【{}】的施工人员列表，共{}人",
                    workPlan.getPlanName(), workers.size());
            return workers;

        } catch (Exception e) {
            log.error("获取工作计划{}的施工人员列表失败：{}", workPlanId, e.getMessage());
            return new ArrayList<>();
        }
    }

    @Override
    public List<Integer> getGuardianIdsByWorkPlanId(Integer workPlanId) {
        if (workPlanId == null){
            return emptyList();
        }
        WorkPlan workPlan = appWorkPlanMapper.getWorkPlanById(workPlanId);
        if (workPlan == null) {
            log.warn("未找到ID为{}的工作计划", workPlanId);
            return new ArrayList<>();
        }
        return getGuardianIds(workPlan);
    }

    @Override
    public boolean sendAlarmMessageToWorkPlanGuardians() {

        long startTime = System.currentTimeMillis();
        int processedCount = 0;
        int successCount = 0;
        try {
            List<AppEmpWorkPlanWarnDTO> warnDTOList = appEmpWorkPlanWarnService.getAllWorkPlanWarns();

            if (CollectionUtils.isEmpty(warnDTOList)) {
                log.info("未查询到需要处理的工作计划报警列表");
                return false;
            }

            log.info("开始处理工作计划报警列表，共{}条记录", warnDTOList.size());

            for (AppEmpWorkPlanWarnDTO warnDTO : warnDTOList) {
                processedCount++;
                try {
                    if (processSingleAlarm(warnDTO)) {
                        successCount++;
                    }
                } catch (Exception e) {
                    log.error("处理报警记录失败，warnId: {}, planId: {}",
                            warnDTO.getWarnId(), warnDTO.getPlanId(), e);
                }
            }

            long costTime = System.currentTimeMillis() - startTime;
            log.info("工作计划报警处理完成，处理总数：{}，成功：{}，失败：{}，耗时：{}ms",
                    processedCount, successCount, processedCount - successCount, costTime);

            return successCount > 0;

        } catch (Exception e) {
            log.error("工作计划报警处理任务执行异常", e);
            throw new BizException(ResultEnum.FAILURE.getCode(), "工作计划报警处理失败");
        }
    }

    private boolean processSingleAlarm(AppEmpWorkPlanWarnDTO warnDTO) {
        Integer warnId = warnDTO.getWarnId();
        if (warnId == null) {
            log.warn("报警记录ID为空，跳过处理");
            return false;
        }
        String guardian3Id = warnDTO.getGuardian3Id();
        String guardian4Id = warnDTO.getGuardian4Id();
        boolean sendGuardian3Flag = false;
        boolean sendGuardian4Flag = false;
        List<AppMessage> appMessages = messageService.searchAllByMsgObjectId(""+warnId);
        if (CollectionUtils.isEmpty(appMessages)) {
            log.info("报警ID {} 没有已发送的消息记录，跳过处理", warnId);
            return false;
        }
        AppMessage appMessageFirst = appMessages.get(0);
        List<Integer> guardian3Ids = buildGuardianIds(guardian3Id);
        List<Integer> guardian3UserIds = new ArrayList<>();
        List<Integer> guardian4Ids = buildGuardianIds(guardian4Id);
        List<Integer> guardian4UserIds = new ArrayList<>();

        Set<Integer> msgChannelSet = new HashSet<>();
        // 报警间隔时间判断
        if (!shouldSendAlarm(appMessages, warnId)) return false;
        // 监理和业主的报警法中状态
        for (AppMessage appMessage: appMessages){
            for (Integer id : guardian3Ids){
                SysEmpUser sysEmpUser = sysUserService.getEmpUser(id);
                if (sysEmpUser == null) continue;
                guardian3UserIds.add(sysEmpUser.getSysUserId());
                if (appMessage.getToUserId().equals(sysEmpUser.getSysUserId())){
                    sendGuardian3Flag = true;
                }
            }
            for (Integer id : guardian4Ids){
                SysEmpUser sysEmpUser = sysUserService.getEmpUser(id);
                if (sysEmpUser == null) continue;
                guardian4UserIds.add(sysEmpUser.getSysUserId());
                if (appMessage.getToUserId().equals(sysEmpUser.getSysUserId())){
                    sendGuardian4Flag = true;
                }
            }
            // 设置报警渠道
            msgChannelSet.add(appMessage.getMsgChannel());
        }

        List<AppMsgToUserDTO> toUserList = new ArrayList<>();
        if (!sendGuardian3Flag && !CollectionUtils.isEmpty(guardian3UserIds)){
            fillToUserList(warnDTO, guardian3UserIds, appMessageFirst, toUserList);
        }else if (!sendGuardian4Flag && !CollectionUtils.isEmpty(guardian4UserIds)){
            fillToUserList(warnDTO, guardian4UserIds, appMessageFirst, toUserList);
        }
        sendMessage(appMessageFirst, new ArrayList<>(msgChannelSet), toUserList);
        return true;
    }

    private boolean shouldSendAlarm(List<AppMessage> appMessages, Integer warnId) {
        Date lastAlarmTime = appMessages.stream()
                .map(AppMessage::getTime)
                .max(Date::compareTo)
                .orElse(null);
        Date currentDate = new Date();
        if (lastAlarmTime != null && DateUtil.addMinutes(lastAlarmTime, helmetProperties.getMinutes()).after(currentDate)){
            log.error("报警信息 {} 报警时间未到,末次报警时间 {}，当前时间 {}", warnId, lastAlarmTime, currentDate);
            return false;
        }
        return true;
    }

    private void fillToUserList(AppEmpWorkPlanWarnDTO warnDTO, List<Integer> guardianUserIds, AppMessage appMessageFirst, List<AppMsgToUserDTO> toUserList) {
        for (Integer id: guardianUserIds) {
            SysUser sysUser = sysUserService.selectByPrimaryKey(id);
            AppMsgToUserDTO toUserDTO = new AppMsgToUserDTO();
            toUserDTO.setUsername(sysUser.getUsername());
            toUserDTO.setRuleId(warnDTO.getRuleId());
            toUserDTO.setUserId(sysUser.getId());
            toUserDTO.setPhone(sysUser.getPhone());
            toUserDTO.setDeptId(appMessageFirst.getDeptId());
            toUserDTO.setNickName(sysUser.getNickname());
            toUserList.add(toUserDTO);
        }
    }

    private void sendMessage(AppMessage appMessage, List<Integer> msgChannelList, List<AppMsgToUserDTO> toUserList){
        if (CollectionUtils.isEmpty(msgChannelList) || CollectionUtils.isEmpty(toUserList)) {
            return;
        }
        PushMsgDTO pushMsgDTO = new PushMsgDTO();
        BeanUtils.copyProperties(pushMsgDTO, appMessage);
        pushMsgDTO.setMsgChannelList(msgChannelList);
        pushMsgDTO.setToUserList(toUserList);
        amqpTemplate.convertAndSend(QueueConst.PUSH_MSG_EXCHANGE, "", JSONObject.toJSONString(pushMsgDTO));
    }

    /**
     * 从工作计划中解析施工人员ID列表
     */
    private List<String> parseConstructionWorkerIds(AppWorkPlan workPlan) {
        List<String> workerIds = new ArrayList<>();

        if (workPlan.getConstructionWorkers() != null && !Objects.equals(workPlan.getConstructionWorkers(), "")) {
            if (!workPlan.getConstructionWorkers().contains(",")) {
                workerIds.add(workPlan.getConstructionWorkers());
            } else {
                workerIds.addAll(Arrays.asList(workPlan.getConstructionWorkers().split(",")));
            }
        }

        return workerIds;
    }

    /**
     * 获取施工人员详细信息
     */
    private List<AppEmp> getWorkerDetails(List<String> sysUserIds) {
        if (sysUserIds == null || sysUserIds.isEmpty()) {
            return new ArrayList<>();
        }

        try {
            // 将字符串ID转换为整数列表
            List<Integer> empIds = sysUserIds.stream()
                    .map(String::trim)
                    .filter(s -> !s.isEmpty())
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());

            // 批量查询人员信息
            List<AppEmpDTO> empDTOList = appEmpMapper.selectByPrimaryKeyList(empIds);
            if (empDTOList == null || empDTOList.isEmpty()) {
                log.warn("未找到ID为{}的施工人员信息", empIds);
                return new ArrayList<>();
            }

            // 将AppEmpDTO转换为AppEmp
            List<AppEmp> workers = new ArrayList<>();
            for (AppEmpDTO empDTO : empDTOList) {
                AppEmp emp = new AppEmp();
                BeanUtils.copyProperties(empDTO, emp);
                workers.add(emp);
            }

            return workers;

        } catch (Exception e) {
            log.error("获取施工人员详细信息失败：{}", e.getMessage());
            return new ArrayList<>();
        }
    }

}